// flame: 1.17.0 #1.19.0 (需要dart 3.4.0;目前 3.3.4) #https://pub.dev/packages/flame/ flutter游戏引擎框架
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:aio/aio.dart';

//components 游戏引擎组件
import 'package:flame/components.dart';

//events 游戏引擎点击事件
import 'package:flame/events.dart';
import 'package:flame/extensions.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame/palette.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:game/src/keyboard/hardware_keyboard.dart';
import 'package:game/src/mouse/mouse_event.dart';

import 'dart:ffi' as ffi;
import 'package:game/src/utils/image_path_utils.dart';

import '../utils/canvas_utils.dart';

Widget testGameWidget() {
  ///GameWidget 用于存放FlameGame游戏组件。
  ///GameWidget放在Container的时候，Container最好设置高度。不然可能异常。
  ///GameWidget 也可以直接放在runApp()里。

  ///鼠标监听
  // MouseEventManage.startListening();
  var gameWidget = GameWidget(
    game: GameRote(),
    autofocus: false,
    focusNode: FocusNodeManager.getFocusNode("key_game_focusNode").focusNode,
    key: Key("key_GameWidget"),
  );
  return gameWidget;
}

///简单的游戏视图案例
class GameRote extends FlameGame with TapCallbacks {
  ///初始化
  @override
  FutureOr<void> onLoad() {
    // TODO: implement onLoad
    super.onLoad();
    add(_Square("key100_200", Vector2(100, 200)));
    // add(_Square2(Vector2(100, 200)));
  }

  ///生命周期监听
  @override
  void lifecycleStateChange(ui.AppLifecycleState state) {
    // TODO: implement lifecycleStateChange
    super.lifecycleStateChange(state);
  }

  @override
  void onTapUp(TapUpEvent event) {
    // TODO: implement onTapUp
    super.onTapUp(event);
    PositionComponent? _positionComponent = null;
    HardwareKeyboardManage.getAllListener().forEach((key, value) {
      if (value.isFocuse) {
        _positionComponent = value?.positionComponent;
      }
      value?.isFocuse = false;
    });
    Vector2? _position = null;

    ///fixme 注意 Vector2 位置，x,y是组件的中心坐标位置。
    if (_positionComponent != null) {
      var _prePosition = _positionComponent!.position; //上一个选中组件的位置
      var _localPosition = event.localPosition; //当前点击的位置
      _position = Vector2(_localPosition.x, _localPosition.y);
      //====================================垂直方向
      if (_localPosition.y < (_prePosition.y - _squareSize / 2) &&
          _localPosition.y >= (_prePosition.y - _squareSize * 2)) {
        //在上一个选中组件的上边
        _position.y = _prePosition.y - _squareSize;
        _position.x = _prePosition.x;
      } else if (_localPosition.y > (_prePosition.y + _squareSize / 2) &&
          _localPosition.y <= (_prePosition.y + _squareSize * 2)) {
        //在上一个选中组件的下边
        _position.y = _prePosition.y + _squareSize;
        _position.x = _prePosition.x;
      } else {
        //==================================水平方向
        if (_localPosition.x < _prePosition.x &&
            _localPosition.x >= (_prePosition.x - _squareSize * 2)) {
          //在上一个选中组件的左边
          _position.x = _prePosition.x - (_squareSize);
          _position.y = _prePosition.y;
        } else if (_localPosition.x > _prePosition.x &&
            _localPosition.x <= (_prePosition.x + _squareSize * 2)) {
          //在上一个选中组件的右边
          _position.x = _prePosition.x + (_squareSize);
          _position.y = _prePosition.y;
        }
      }
    }
    if (_position == null) {
      _position = event.localPosition;
    }
    //点击松开,添加新的组件。
    add(_Square("key${event.localPosition}", _position));
  }
}

//组件大小
const _squareSize = 32.0; //128.0;

///BasicPalette 基本的调色板
Paint _white = BasicPalette.white.paint();
Paint _red = BasicPalette.red.paint();
Paint _blue = BasicPalette.blue.paint();

ui.Image? _image = null;

///基础 PositionComponent 位置组件
class _Square extends PositionComponent with TapCallbacks {
  String _key = "_Square";

  _Square(String key, Vector2 position) : super(position: position) {
    _key = key;
  }

  ///onLoad()组件初始化时调用一次。
  @override
  Future<void> onLoad() async {
    ///print("=====================================================================onLoad()");
    super.onLoad();

    ///size 组件的大小
    size.setValues(_squareSize, _squareSize);

    ///anchor 锚点；position相对组件自身的相对位置。
    ///Anchor.center position在组件的中心。
    anchor = Anchor.center;
    //anchor = Anchor.bottomLeft;

    //String path="/data/user/0/cn.flutter.plugin.aio_example/cache/image_picker801655351955222340.jpg";
    ///data/user/0/cn.flutter.plugin.aio_example/cache/image_picker102176254354172413.jpg
    // String path = ImagePathUtils.getPathWithImageBall("排球.png");
    if (_image == null) {
      String path = ImagePathUtils.getPathWithImageBrick("24gf-bricks.png");
      CanvasUtils.getAssetImage(path, width: _squareSize.toInt())
          ?.then((value) {
        _image = value;
      });
    }
    //获取按键监听
    _keyBoardBean = HardwareKeyboardManage.getListener(_key);
    _keyBoardBean?.positionComponent = this;
  }

  //按键监听
  KeyBoardBean? _keyBoardBean = null;

  ///update()实时刷新；会实时调用。调用完成之后会马上调用render()方法。
  @override
  void update(double dt) {
    ///dt:0.016667 平均为1秒60帧。 1/0.0166=60
    ///时间[dt]，以秒为单位(flutter提供微秒精度);可以理解为刷新一帧的耗时。
    // print("=====================================================================update() dt:$dt");
    super.update(dt);
    var _value = _keyBoardBean;
    if (_value != null && _value.isFocuse) {
      if (_value.isClear) {
        ///清除
        removeFromParent();
        HardwareKeyboardManage.removeListener(_key);
        return;
      }
      var _x = _value.x;
      var _y = _value.y;
      var _r = _value.r;

      ///angle 组件的角度。
      ///position 组件的位置
      // angle += speed * dt;
      // angle %= 2 * math.pi;
      // position.x += _x * dt;
      // position.y += _y * dt;
      position.x += _x;
      position.y += _y;
      // if (_x > 0) {
      //   angle += speed * dt;
      // } else if (_x < 0) {
      //   angle -= speed * dt;
      // } else if (_y > 0) {
      //   angle += speed * dt;
      // } else if (_y < 0) {
      //   angle -= speed * dt;
      // }
      angle += _r * dt;
    }
  }

  ///render()画布渲染。也是实时调用渲染。update()调用一次，render()也会调用一次；如：
  // update() dt:0.0
  // render()
  // update() dt:0.033333
  // render()
  // update() dt:0.05
  // render()
  @override
  void render(Canvas c) {
    // print("=====================================================================render()");
    //c.drawRect(size.toRect(), white);
    // c.drawRect(const Rect.fromLTWH(0, 0, 3, 3), red);
    // c.drawRect(Rect.fromLTWH(width / 2, height / 2, 3, 3), blue);
    //c.drawCircle(Offset(width/2, height/2), width/2, white);//画圆
    if (_image != null) {
      _white.color = Colors.white;
      _white.colorFilter =
          ui.ColorFilter.mode(Colors.red, ui.BlendMode.srcIn); //fixme 修改图片的颜色
      c.drawImage(_image!, Offset(0, 0), _white);
    }
  }

  @override
  void onTapDown(TapDownEvent event) {
    // TODO: implement onTapDown
    super.onTapDown(event);
    //event.localPosition;//当前点击位置
    // removeFromParent();//组件移除

    HardwareKeyboardManage.getAllListener().forEach((key, value) {
      value?.isFocuse = false;
    });
    _keyBoardBean?.isFocuse = true;
    //event.pointerId 点击id;没点一次，就会增长一次，每次都不同。不能作为唯一标志。
    // 点击按下:PointerDeviceKind.mouse
    // print("点击按下:${event.deviceKind}");
  }
}

class _Square2 extends RectangleComponent with TapCallbacks {
  static const speed = 3;
  static const squareSize = 128.0;
  static const indicatorSize = 6.0;

  static final Paint red = BasicPalette.red.paint();
  static final Paint blue = BasicPalette.blue.paint();

  _Square2(Vector2 position)
      : super(
          position: position,
          size: Vector2.all(squareSize),
          anchor: Anchor.center,
        );

  @override
  Future<void> onLoad() async {
    super.onLoad();
    add(
      RectangleComponent(
        size: Vector2.all(indicatorSize),
        paint: blue,
      ),
    );
    add(
      RectangleComponent(
        position: size / 2,
        size: Vector2.all(indicatorSize),
        anchor: Anchor.center,
        paint: red,
      ),
    );
  }

  @override
  void update(double dt) {
    super.update(dt);
    angle += speed * dt;
    angle %= 2 * math.pi;
  }

  @override
  void onTapDown(TapDownEvent event) {
    removeFromParent();
    event.handled = true;
  }
}
